//
//  RankController.m
//  GameModules
//
//  Created by hyc on 16/6/29.
//  Copyright © 2016年 hyc. All rights reserved.
//

#import "RankController.h"
#import <GameKit/GameKit.h>
#import "PlayerModel.h"

@interface RankController ()<GKLeaderboardViewControllerDelegate>

@property(readwrite, retain) PlayerModel * player;
@property(nonatomic,assign)BOOL isLogin;

@end

@implementation RankController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [[GKLocalPlayer localPlayer] setAuthenticateHandler:(^(UIViewController* viewcontroller, NSError *error) {
        if (viewcontroller) {
            [self presentViewController:viewcontroller animated:YES completion:nil];
        }
    })];
    
    NSNotificationCenter* ns = [NSNotificationCenter defaultCenter];
    [ns addObserver:self selector:@selector(authenticationChanged) name:GKPlayerAuthenticationDidChangeNotificationName object:nil];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 200, 44)];
    btn.backgroundColor = [UIColor blueColor];
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void) authenticationChanged
{
    if ([GKLocalPlayer localPlayer].isAuthenticated) {
        NSLog(@"authenticationChanged, authenticated");
        [self updatePlayer];
        self.isLogin = YES;
    }
    else
    {
        NSLog(@"authenticationChanged, Not authenticated");
        self.isLogin = NO;
    }
}

- (void) updatePlayer
{
    if (!self.player || ![self.player.currentPlayerID isEqualToString:[GKLocalPlayer localPlayer].playerID]) {
        self.player = [[PlayerModel alloc] init];
    }
    [[self player] loadStoredScores];
}

- (void)showGameCenter
{
    if (self.isLogin) {
        GKLeaderboardViewController * leaderboardViewController = [[GKLeaderboardViewController alloc] init];
        [leaderboardViewController setCategory:@"yical.tianti"];
        [leaderboardViewController setLeaderboardDelegate:self];
        [self presentViewController:leaderboardViewController animated:YES completion:nil];
    }
}

- (void)click:(UIButton *)btn {
    [self showGameCenter];
}

#pragma mark - 排行榜delegate

- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController{
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

@end
